<template>
  <div
    class="flex h-full w-full items-center justify-self-start overflow-hidden"
  >
    <div class="h-full w-fit overflow-hidden">
      <div class="w-66 z-10 h-full bg-[rgba(0,0,0,.3)] p-3">
        <div class="flex items-center justify-between">
          <div class="module-title mb-0">二维场景</div>
          <Button @click="() => toggleConfig(!isConfig)">{{
            isConfig ? '返回' : '配置'
          }}</Button>
        </div>
        <Transition name="zoom-in-center">
          <div v-if="isConfig" class="relative">
            <h1 class="mb-1 text-base font-bold">测点列表</h1>
            <ul @dragover.prevent="">
              <li
                v-for="(item, index) in pointList"
                :key="index"
                class="mb-4 flex w-full items-center justify-between"
                :class="{ grayscale: item.top || item.left }"
              >
                <img
                  class="mr-4 h-6 w-6 select-none"
                  src="/static/devices/measure-point.png"
                  :draggable="!item.top || !item.left"
                  @dragstart="() => dragstart()"
                  @dragend="(e) => dragend(e, item, !!item.top || !!item.left)"
                />
                <Tooltip>
                  <template #title>
                    <div class="grid grid-cols-2">
                      <span>测点名称：</span>
                      <span>{{ item.pointName }}</span>
                      <span>设备编号：</span>
                      <span>{{ item.stationId }}</span>
                      <span>序列号：</span>
                      <span>{{ item.deviceCode }}</span>
                      <span>位置：</span>
                      <span>{{ item.location }}</span>
                    </div>
                  </template>
                  <span class="flex-1 select-none">{{ item.pointName }}</span>
                </Tooltip>
                <Button
                  type="text"
                  @click="() => onClean(item)"
                  :disabled="!item.top"
                  >清除</Button
                >
              </li>
            </ul>
          </div>
          <div v-else>
            <div class="mb-4">
              <h1 class="mb-1 text-base font-bold">名称</h1>
              <div>{{ structureName }}</div>
            </div>
            <div class="mb-4">
              <h1 class="mb-1 text-base font-bold">关联设备</h1>
              <ul>
                <li
                  v-for="(item, index) in deviceList"
                  :key="index"
                  class="mb-4 flex w-full items-center justify-between"
                >
                  <img class="mr-4 h-6 w-6" :src="item.url" />
                  <span class="flex-1">{{ item.label }}</span>
                  <span>{{ item.value }}</span>
                </li>
              </ul>
            </div>
          </div>
        </Transition>
      </div>
    </div>
    <div ref="containerRef" class="relative ml-4 aspect-[1080/964] h-full">
      <Button class="!absolute right-3 top-3 z-10" @click="() => onGoBack()"
        >返回列表页</Button
      >
      <div class="point-wrap z-1 relative h-full w-full" @dragover.prevent="">
        <template v-for="(item, idx) in pointList" :key="idx">
          <Tooltip v-if="item.top && item.left">
            <template #title>{{ item.pointName }}</template>
            <a
              class="absolute"
              :style="{ top: item.top, left: item.left }"
              @dragstart="() => dragstart()"
              @dragend="(e) => dragend(e, item)"
              @click="() => handlePreviewWave(item)"
              @click.right.prevent="handlePreview(item)"
            >
              <img
                src="/static/devices/measure-point.png"
                class="h-6 w-6 select-none"
              />
            </a>
          </Tooltip>
        </template>
      </div>
      <img class="absolute left-0 top-0 h-full w-full" :src="photoUrl" />
    </div>
  </div>

  <FormModal />
  <Modal
    title="实时波形"
    v-model:open="visible"
    destroy-on-close
    :width="1100"
    :footer="false"
  >
    <Wave :stationId="currentStationId"></Wave>
  </Modal>
</template>
<route lang="json">
{
  "meta": {
    "title": "场景预览",
    "requireAuth": false,
    "hideInTabs": true
  }
}
</route>

<script setup lang="tsx">
import { computed, ref, useTemplateRef } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { useToggle } from '@vueuse/core';
import { Button, Modal, Tooltip, message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { preview, updatePosition } from './api';
import Device from './components/device.vue';
import Wave from './components/wave.vue';

const router = useRouter();

const [isConfig, toggleConfig] = useToggle(false);
const isDragger = ref(false);

const { deviceTypeEnum } = useDicts(['device_type']);

const params = history.state;
const { id, structureName, photoUrl } = params;

(async () => {
  const res = await preview(id);
  deviceTypes.value = res.data.deviceTypes;
  pointList.value = res.data.pointList;
})();

enum ImageEnum {
  'seismograph' = 1,
  'power',
  'terminal',
}

const deviceTypes = ref(undefined);

const deviceList = computed(() => {
  if (deviceTypes.value) {
    return Object.keys(deviceTypes.value).map((key) => {
      return {
        label: deviceTypeEnum.value[key]?.text,
        value: deviceTypes.value[key],
        url: `/static/devices/${ImageEnum[key]}.png`,
      };
    });
  }
  return [];
});

const pointList = ref([]);

const updatePoint = () => {
  const list = pointList.value.map((item) => {
    return {
      pointId: item.id,
      left: item.left,
      top: item.top,
    };
  });
  updatePosition(list);
};

const container = useTemplateRef('containerRef');
const calcPosition = (e) => {
  const rect = container.value.getBoundingClientRect();
  //计算盒子距离图片盒子精确距离
  const currentLeft = e.clientX - rect.left - 12;
  const currentTop = e.clientY - rect.top - 12;
  if (
    currentLeft < 0 ||
    currentTop < 0 ||
    currentLeft > rect.width ||
    currentTop > rect.height
  ) {
    message.info('超出可添加设备范围!');
    return;
  }
  const left = ((currentLeft / rect.width) * 100).toFixed(4) + '%';
  const top = ((currentTop / rect.height) * 100).toFixed(4) + '%';

  return {
    left,
    top,
  };
};
const dragstart = () => {
  if (!isConfig.value) return;
  isDragger.value = true;
};

const dragend = (e, record, disabled = false) => {
  if (!isConfig.value) return;
  if (disabled) return;
  const result = calcPosition(e);
  if (result) {
    const { top, left } = result;
    record.top = top;
    record.left = left;
    updatePoint();
  }
  isDragger.value = false;
};

const onClean = (record) => {
  console.log(record);

  pointList.value = pointList.value.map((item) => {
    if (item.id === record.id) {
      item.top = null;
      item.left = null;
    }
    return item;
  });

  console.log(pointList.value);

  updatePoint();
};

const { FormModal, open } = useFormModal({
  column: 2,
  size: 'middle',
  bodyHeight: '72vh',
  items: [
    {
      title: '',
      valueType: 'input',
      dataIndex: '_i',
      formItemRender() {
        return <div class='module-title'>描点信息</div>;
      },
      colProps: { span: 24 },
      formItemProps: {
        labelCol: { span: 0 },
        wrapperCol: { span: 24 },
      },
    },
    {
      title: '测点名称',
      dataIndex: 'pointName',
      valueType: 'input',
    },
    {
      title: '测点位置',
      dataIndex: 'location',
      valueType: 'input',
    },
    {
      title: '',
      valueType: 'input',
      dataIndex: '_i',
      formItemRender() {
        return <div class='module-title'>设备信息</div>;
      },
      colProps: { span: 24 },
      formItemProps: {
        labelCol: { span: 0 },
        wrapperCol: { span: 24 },
      },
    },
    {
      title: '',
      valueType: 'input',
      dataIndex: '_i',
      colProps: { span: 24 },
      formItemProps: {
        labelCol: { span: 0 },
        wrapperCol: { span: 24 },
      },
      formItemRender(state) {
        return <Device device={state as any} />;
      },
    },
  ],
});
const handlePreview = (item) => {
  open({
    title: '设备信息',
    defaultValue: { ...item },
    modalType: 'disabled',
    async request() {},
  });
};

// const handleClick = (e) => {
//   if (!isConfig.value) return;
//   const rect = container.value.getBoundingClientRect();
//   const currentLeft = e.clientX - rect.left;
//   const currentTop = e.clientY - rect.top;
//   const left = ((currentLeft / rect.width) * 100).toFixed(4) + '%';
//   const top = ((currentTop / rect.height) * 100).toFixed(4) + '%';
//   open({
//     title: '配置描点',
//     items: [
//       {
//         title: '',
//         valueType: 'input',
//         dataIndex: '_i',
//         formItemRender() {
//           return <div class='module-title'>描点信息</div>;
//         },
//         colProps: { span: 24 },
//         formItemProps: {
//           labelCol: { span: 0 },
//           wrapperCol: { span: 24 },
//         },
//       },
//       {
//         title: '测点名称',
//         dataIndex: 'id',
//         valueType: 'select',
//         fieldProps: {
//           options: pointList.value.map((item) => {
//             return {
//               label: item.pointName,
//               value: item.id,
//             };
//           }),
//         },
//       },
//       {
//         title: '',
//         valueType: 'input',
//         dataIndex: '_i',
//         formItemRender() {
//           return <div class='module-title'>设备信息</div>;
//         },
//         colProps: { span: 24 },
//         formItemProps: {
//           labelCol: { span: 0 },
//           wrapperCol: { span: 24 },
//         },
//       },
//       {
//         title: '',
//         valueType: 'input',
//         dataIndex: '_i',
//         colProps: { span: 24 },
//         formItemProps: {
//           labelCol: { span: 0 },
//           wrapperCol: { span: 24 },
//         },
//         formItemRender(state) {
//           const device = pointList.value.find((item) => item.id === state.id);
//           return <Device device={device as any} hideMonitor />;
//         },
//       },
//     ],
//     request: async function ({ id }: any) {
//       pointList.value.forEach((item) => {
//         if (item.id === id) {
//           item.top = top;
//           item.left = left;
//         }
//       });
//       await updatePoint();
//     },
//   });
// };

const visible = ref(false);
const currentStationId = ref('');
const handlePreviewWave = (item) => {
  currentStationId.value = item.stationId;
  visible.value = true;
};

const onGoBack = () => {
  router.back();
};
</script>
